import { Component, Input, ViewChild, EventEmitter, Output, Host } from "@angular/core";
import { LongRunningTaskTypeEnum, LrtmService } from "../../../../framework/lrtm/lrtm.service";
import { FilterModel, FilterType, ExportType } from "../../models/filter.model";
import { UtilsService } from "../../../../shared/services/utils.service";
import { TargetType, ReportingService } from "../../reporting.service";
import { ModalComponent } from "../../../../shared/components/modal/modal.component";
import { PortfolioService } from "../../../portfolio/portfolio.service";
import { PortfolioFilterModel } from "../../../portfolio/models/portfolioFilter.model";
import { PortfolioType } from "../../../portfolio/models/portfolioType.model";
import { CompanySearchComponent } from "../../../../shared/components/search/company-search/company-search.component";
import { PortfolioSharingStatus } from "../../../portfolio/models/portfolioSharingStatus.model";
import { SortablejsOptions } from "angular-sortablejs/dist";
import { CriteriaModel } from "../../models/criteriaResult.model";
import { SearchType } from "../../../../shared/components/search/search.service";
import { AppComponent } from "../../../../app.component";
import { SearchComponent } from "../../../../shared/components/search/search.component";
import swal, { SweetAlertOptions } from "sweetalert2";
import { AnalyticsService } from "../../../../shared/services/googleAnalytics.service";
import { GoogleAnalyticsBeacon } from "../../../../shared/models/googleAnalytics.model";

@Component({
    selector: 'filter-export',
    templateUrl: 'export.component.html',
    styleUrls: ['../../reporting.component.scss']
})
export class FilterExportComponent {
    public type: LongRunningTaskTypeEnum;
    public sharePortfolio: boolean = false;
    public targetType: typeof TargetType = TargetType;
    public filterType: typeof FilterType = FilterType;
    public lrtmType: typeof LongRunningTaskTypeEnum = LongRunningTaskTypeEnum;
    public sortableOptions: SortablejsOptions;
    public searchType: SearchType = SearchType.portfolio;    

    @ViewChild('portfolioModal') portfolioModal: ModalComponent;

    @ViewChild('portfolioSearch') portfolioSearch: SearchComponent;

    @Input() filter: FilterModel;

    @Input() count: number;

    @Input() columns: CriteriaModel[];

    @Output() reorder: EventEmitter<CriteriaModel[]> = new EventEmitter();

    @Output() portfolioSaved: EventEmitter<void> = new EventEmitter<void>();

    constructor(
        private rootComponent: AppComponent,
        private lrtmService: LrtmService,
        private toolsService: ReportingService,
        private portfolioService: PortfolioService,
        private analyticsService: AnalyticsService) {
        this.sortableOptions = {
            ghostClass: 'ghost',
            onSort: _ => { this.sortableOnSort(); }
        };
    }

    public generateReport() {
        this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon(
            this.filter.targetType == TargetType.Screening ? 
                (this.type == LongRunningTaskTypeEnum.ScreeningToolCSV ? 'CSVCustomFilter' : 'ExcelCustomFilter') : 
                (this.type == LongRunningTaskTypeEnum.ScreeningToolCSV ? 'CSVCustomReport' : 'ExcelCustomReport'), 
            this.filter.targetType == TargetType.Screening ? 'Screening Tool' : 'Reporting Tool', { FilterId: this.filter.id }));

        //save exportType:
        this.filter.exportType = this.type == LongRunningTaskTypeEnum.ScreeningToolCSV ? ExportType.CSV : ExportType.Excel;
        this.toolsService.updateFilter(this.filter, true).subscribe(_=>{
            this.lrtmService.runTask(this.rootComponent, this.filter.name + "_" + UtilsService.getReportDate(), this.type, this.filter.id, true).subscribe(_ => { });
        });
    }

    public savePortfolio() {
        this.sharePortfolio = false;
        this.portfolioModal.show();
    }

    public saveAsPortfolio() {
        let filter: PortfolioFilterModel = new PortfolioFilterModel();
        filter.portfolioType = PortfolioType.All;
        filter.portfolioId = this.portfolioSearch.selected != null ? this.portfolioSearch.selected.id: null;
        filter.namePortfolio = this.portfolioSearch.selected != null ? this.portfolioSearch.selected.name : this.portfolioSearch.term;
        filter.sharingStatus = PortfolioSharingStatus.All;
        filter.isNameEqual = true;

        this.portfolioService.getPortfolioCount(filter).subscribe(count => {
            if (count == 0 || count == null) {
                this.portfolioSave(filter.portfolioId, filter.namePortfolio, false);
            } else if (count >= 1) {
                const swalOptions: SweetAlertOptions = Object.assign(UtilsService.getBaseSwalOptions(), {
                    title: 'Overwrite Portfolio',
                    text: 'Are you sure you want to overwrite the existing portfolio?',
                    confirmButtonClass: 'btn btn-primary',
                    confirmButtonText: 'Overwrite',
                    imageUrl: '/assets/icons-svg/icon-warning.svg'
                });

                swal(swalOptions).then(result => {
                    if (result && result.value) {
                        this.portfolioSave(filter.portfolioId, filter.namePortfolio, true);
                    }
                });                
            }
            this.portfolioModal.hide();
        });
    }

    private portfolioSave(portfolioId: string, portfolioName: string, update: boolean) {
        this.portfolioService.savePortfolio(this.filter.id, portfolioId, portfolioName, this.sharePortfolio, update).subscribe(_ => {
            this.portfolioModal.hide();
            this.portfolioSaved.emit();
        });
    }

    public cancelPortfolioModal() {
        this.portfolioSearch.term ='';
        this.portfolioModal.hide();
    }

    private getSortOrder() {
        return [].map.call(document.querySelectorAll('[data-key]'), (element) => {
            return element.dataset.key;
        });
    }

    private sortableOnSort() {
        // get the sorted IDs
        const ids: string[] = this.getSortOrder();
        this.toolsService.reorderResultColumns(this.filter.id, ids).subscribe(_ => {
            this.reorder.emit(this.columns);
        });
    }
}